<script setup lang="ts">
import type { ReceiptClaimRecordDetails } from '@/api/types/system'
import type { InfoItem } from '@/components/DetailCard.vue'
import { onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { getSysClaimRecordDetails } from '@/api/system'
import ApprovalActionBar from '@/components/ApprovalActionBar.vue'
import ApprovalStatusCard from '@/components/ApprovalStatusCard.vue'
import DetailCard from '@/components/DetailCard.vue'
import { useFlow } from '@/hooks/useFlow'

// 定义页面配置
definePage({
  style: {
    navigationBarTitleText: '资金认领详情',
  },
})

// 使用流程相关功能
const { currentProcess, getProcessInstance, getCurrentUserPendingTaskId, loading } = useFlow()

// 业务详情数据
const businessData = ref<ReceiptClaimRecordDetails | null>(null)
const errorMessage = ref('')
const flowIdValue = ref<string>('')
const idValue = ref<string>('')

// 获取业务详情数据
async function getBusinessData() {
  try {
    await getProcessInstance(idValue.value)
    // 获取当前用户待审批任务ID
    const taskId = await getCurrentUserPendingTaskId(idValue.value)
    if (taskId) {
      flowIdValue.value = taskId
    }
    if (!currentProcess.value) {
      return
    }
    else {
      const res = await getSysClaimRecordDetails(currentProcess.value.businessKey)
      businessData.value = res.data || null
    }
  }
  catch (error) {
    console.error('获取业务详情失败:', error)
    errorMessage.value = '获取业务详情失败，请重试'
  }
}

// 认领金额信息卡片数据
const claimAmountInfo = computed<InfoItem[]>(() => {
  const data = businessData.value
  if (!data)
    return []
  return [
    { label: '认领金额', value: data.claimAmount, type: 'currency' },
    { label: '资金类型', value: data.fundsType === 1 ? '运费' : '其他' },
    { label: '资金认领业务单号', value: data.receiptClaimBusinessNo || '-' },
    { label: '结算类型', value: data.settlementType === 1 ? '货主结算' : '承运商结算' },
    { label: '费用名称', value: data.costName || '-' },
    { label: '创建人', value: data.createName || '-' },
    { label: '创建时间', value: data.createTime || '-' },
    { label: '结算单号', value: data.settlementNo || '-' },
    { label: '审批状态', value: data.approvalStatus || 0, type: 'approval' },
  ]
})

// 收款记录信息卡片数据
const receiptRecordInfo = computed<InfoItem[]>(() => {
  const data = businessData.value?.receiptRecord
  if (!data)
    return []
  return [
    { label: '收款业务单号', value: data.businessNo || '-' },
    { label: '收款金额', value: data.amount, type: 'currency' },
    { label: '剩余金额', value: data.remainingAmount, type: 'currency' },
    { label: '款项类型', value: data.receiptEvent || '-' },
    { label: '收款主体', value: data.receivingEntity || '-' },
    { label: '收款账户', value: data.receivingAccount || '-' },
    { label: '收款银行', value: data.receivingBank || '-' },
    { label: '收款时间', value: data.payTime || '-' },
    { label: '付款主体', value: data.payerEntity || '-' },
    { label: '付款账户', value: data.payerAccount || '-' },
    { label: '付款银行', value: data.payerBank || '-' },
    { label: '收款备注', value: data.remark || '无', forceMultiline: true },
  ]
})

// 结算信息卡片数据
const settlementInfo = computed<InfoItem[]>(() => {
  const data = businessData.value?.settlementInfo
  if (!data)
    return []
  return [
    { label: '结算单号', value: data.settlementNo || '-' },
    { label: '结算金额', value: data.payment, type: 'currency' },
    { label: '实际支付金额', value: data.actualPayment, type: 'currency' },
    { label: '运单号', value: data.waybillNo || '-' },
    { label: '应收日期', value: data.receivableDate || '-' },
    { label: '账单状态', value: data.billStatus === 1 ? '正常' : '异常' },
  ]
})

// 运单信息卡片数据
const waybillInfo = computed<InfoItem[]>(() => {
  const data = businessData.value?.waybillInfo
  if (!data)
    return []
  return [
    { label: '运单订单号', value: data.wayBillOrderNumber || '-' },
    { label: '出发地', value: `${data.startProvince} ${data.startCity} ${data.startArea}` || '-' },
    { label: '目的地', value: `${data.endProvince} ${data.endCity} ${data.endArea}` || '-' },
    { label: '货主价格', value: data.ownerPrice, type: 'currency' },
    { label: '承运商总价', value: data.carrierTotalPrice, type: 'currency' },
    { label: '车辆类型', value: data.carType || '-' },
    { label: '业务员', value: data.salesmanName || '-' },
    { label: '发布时间', value: data.releaseTime || '-' },
  ]
})

// 页面加载时获取数据
onLoad(async (e: any) => {
  if (e.flowId) {
    flowIdValue.value = e.flowId
  }
  idValue.value = e.id || ''
})

// 页面显示时重新获取数据
onShow(async () => {
  if (idValue.value) {
    await getBusinessData()
  }
})

// 选项卡切换值
const tabValue = ref<number>(0)
</script>

<template>
  <view class="page">
    <!-- 审批状态卡片 -->
    <ApprovalStatusCard :current-process="currentProcess" :id-value="idValue" />

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      加载中...
    </view>

    <!-- 错误状态 -->
    <view v-else-if="errorMessage" class="error-container">
      <text>{{ errorMessage }}</text>
      <button class="retry-btn" @click="getBusinessData">
        重新加载
      </button>
    </view>
    <wd-tabs v-else-if="businessData" v-model="tabValue" swipeable animated sticky :offset-top="0">
      <wd-tab title="资金认领信息" custom-class="bg-[#f9fafb]" class="px-4 py-2.5">
        <!-- 认领金额信息 -->
        <DetailCard title="认领金额信息" :info-list="claimAmountInfo" />

        <!-- 收款记录信息 -->
        <DetailCard title="资金收款信息" :info-list="receiptRecordInfo" />
      </wd-tab>
      <wd-tab title="其他信息" custom-class="bg-[#f9fafb]" class="px-4 py-2.5">
        <!-- 结算信息 -->
        <DetailCard title="结算信息" :info-list="settlementInfo" />

        <!-- 运单信息 -->
        <DetailCard title="运单信息" :info-list="waybillInfo" />
      </wd-tab>
    </wd-tabs>

    <!-- 审批操作栏 -->
    <view class="approval-bar">
      <ApprovalActionBar
        v-if="flowIdValue && currentProcess?.status === 1"
        :process-id="flowIdValue"
      />
    </view>
  </view>
</template>

<style scoped>
.page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.error-container {
  color: #999;
}

.retry-btn {
  margin-top: 16rpx;
  padding: 8px 24px;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
}
</style>
